import json
from collections import defaultdict
import uuid

# 读取 points.json 文件
with open('points.json', 'r', encoding='utf-8') as file:
    points_data = json.load(file)

with open('devices.json', 'r', encoding='utf-8') as file:
    devices_data = json.load(file)

# 遍历原始数据，将其按 OP 类型进行分类并提取五个参数
read_data = defaultdict(list)
for entry in points_data:
    if entry[0] != 'NodeRobot' and entry[0] != 'virtual':
        # 按 OP 类型分类，将五个参数存入字典
        read_data[entry[0]].append(entry)

write_data = defaultdict(list)
for entry in points_data:
    if entry[0] == 'NodeRobot' :
        # 按 OP 类型分类，将五个参数存入字典
        write_data[entry[2]].append(entry)

# 创建一个空列表，用于存储生成的节点信息
node_data = []


with open('fun_read.js', 'r', encoding='utf-8') as file:
    fun_read = file.read()

with open('fun_set.js', 'r', encoding='utf-8') as file:
    fun_set = file.read()    

with open('fun_write.js', 'r', encoding='utf-8') as file:
    fun_write = file.read()      

# 用于跟踪 y 坐标，初始值为 760
y_coordinate = 60

node_data.append({
    "id": "data_center",
    "type": "tab",
    "label": "data_center",
    "disabled": False,
    "info": "",
    "env": []
})

trigger_id = str(uuid.uuid4()).replace('-', '')[:16]
virtual_id = str(uuid.uuid4()).replace('-', '')[:16]

inject_node = {
    "id": str(uuid.uuid4()).replace('-', '')[:16],
    "type": "inject",
    "z": "data_center",
    "name": "",
    "props": [
        {
            "p": "payload"
        },
        {
            "p": "topic",
            "vt": "str"
        }
    ],
    "repeat": "",
    "crontab": "",
    "once": True,
    "onceDelay": "2",
    "topic": "",
    "payload": "",
    "payloadType": "date",
    "x": 100,
    "y": 40,
    "wires": [
        [
           trigger_id,
           virtual_id
        ]
    ]
}

node_data.append(inject_node)

fun_virtual = ""

with open('fun_virtual.js', 'r', encoding='utf-8') as file:
    fun_virtual = file.read()

node_virtual = {
    "id": virtual_id,
    "type": "function",
    "z": "data_center",  # 固定的 z 值
    "name": "virtual",
    "func": fun_virtual,
    "outputs": 1,
    "timeout": 0,
    "noerr": 0,
    "initialize": "",
    "finalize": "",
    "libs": [],
    "x": 250,
    "y": 100,
    "wires": [
        []  # 无后续连接
    ]
}

node_data.append(node_virtual)


trigger_node = {
    "id": trigger_id,
    "type": "trigger",
    "z": "data_center",
    "name": "",
    "op1": "1",
    "op2": "0",
    "op1type": "str",
    "op2type": "str",
    "duration": "-250",
    "extend": False,
    "overrideDelay": False,
    "units": "ms",
    "reset": "",
    "bytopic": "all",
    "topic": "topic",
    "outputs": 1,
    "x": 270,
    "y": 40,
    "wires": [
        [
        ]
    ]
}

for op_type in write_data:
    y_coordinate += 50
    node_id = str(uuid.uuid4()).replace('-', '')[:16]  # 获取 16 位的唯一 id
    next_node_id = str(uuid.uuid4()).replace('-', '')[:16]  # 下一个节点的 id  

    for item in devices_data:
        if item[3] == op_type and item[0] == 'MODBUSTCP':

            # 构建第一个 function 节点
            node_data.append({
                "id": node_id,
                "type": "function",
                "z": "data_center",  # 固定的 z 值
                "name": "写"+op_type,
                "func": fun_write.replace("__NAME__",op_type),
                "outputs": 1,
                "timeout": 0,
                "noerr": 0,
                "initialize": "",
                "finalize": "",
                "libs": [],
                "x": 370,  # 位置坐标
                "y": y_coordinate,  # 使用当前 y 坐标
                "wires": [
                    [next_node_id]  # 下一个节点的 id
                ]
            })

            trigger_node['wires'][0].append(node_id)

            md_write_node = {
                "id": next_node_id,
                "type": "modbus-flex-write",
                "z": "data_center",
                "name": "写"+op_type,
                "showStatusActivities": False,
                "showErrors": False,
                "showWarnings": True,
                "server": "modbus_"+op_type,
                "emptyMsgOnFail": False,
                "keepMsgProperties": False,
                "delayOnStart": False,
                "startDelayTime": "",
                "x": 600,
                "y": y_coordinate,  # 使用当前 y 坐标
                "wires": [
                    [],
                    []
                ]
            }

            node_data.append(md_write_node)

            break


# 遍历 `op_data` 中的每个分类
for op_type in read_data:

    y_coordinate += 50
    
    # 生成唯一的 id，使用 uuid
    node_id = str(uuid.uuid4()).replace('-', '')[:16]  # 获取 16 位的唯一 id
    next_node_id = str(uuid.uuid4()).replace('-', '')[:16]  # 下一个节点的 id
    id3 = str(uuid.uuid4()).replace('-', '')[:16]  # 下一个节点的 id
    
    # 构建第一个 function 节点
    node_data.append({
        "id": node_id,
        "type": "function",
        "z": "data_center",  # 固定的 z 值
        "name": "读"+op_type,
        "func": fun_read.replace("__NAME__",op_type),
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 370,  # 位置坐标
        "y": y_coordinate,  # 使用当前 y 坐标
        "wires": [
            [id3]  # 下一个节点的 id
        ]
    })

    trigger_node['wires'][0].append(node_id)

    # 构建 modbus-flex-getter 节点
    node_data.append({
        "id": id3,
        "type": "modbus-flex-getter",
        "z": "data_center",
        "name": "读"+op_type,
        "showStatusActivities": False,
        "showErrors": False,
        "showWarnings": True,
        "logIOActivities": False,
        "server": "modbus_"+op_type,
        "useIOFile": False,
        "ioFile": "",
        "useIOForPayload": False,
        "emptyMsgOnFail": False,
        "keepMsgProperties": True,
        "delayOnStart": False,
        "startDelayTime": "",
        "x": 600,
        "y": y_coordinate,  # 使用当前 y 坐标
        "wires": [
            [
                next_node_id
            ],
            []
        ]
    })


    # 构建第二个 function 节点
    node_data.append({
        "id": next_node_id,
        "type": "function",
        "z": "data_center",  # 固定的 z 值
        "name": "",
        "func": fun_set,
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 800,  # 位置坐标
        "y": y_coordinate,  # 使用当前 y 坐标
        "wires": [
            []  # 无后续连接
        ]
    })    


node_data.append(trigger_node)

# 打印结果查看
with open('../flows/data_center.json', 'w', encoding='utf-8') as file:
    json.dump(node_data, file, indent=4, ensure_ascii=False)
